class Ems::StoreStaffsController < Ems::BaseController
  before_action :set_store_staff, only: [:destroy, :edit, :update, :pwd, :reset_password]
  def index
    @store_staffs = current_store.store_staffs.includes(:store_department, :store_position).available.without_admin
  end

  def new
    @staff = StoreStaff.new()
  end

  def edit
    @departments = current_store.departments.useable
    @positions = @staff.store_department_id.present? ? @staff.store_department.positions : (@departments[0].try(:store_positions) || [])
  end

  def destroy
    @staff.destroy
    redirect_to ems_store_staffs_path
  end

  def create
    params[:store_staff][:employeed_at] = Time.now
    @store_staff = StoreStaff.new(store_staff_params)
    if @store_staff.save
      redirect_to ems_store_staffs_path
    else
      redirect_to new_ems_store_staff_path, notice: @store_staff.errors.full_messages.first
    end
  end

  def update
    @staff.update(store_staff_params)
    redirect_to ems_store_staffs_path
  end

  def pwd
    @store_id = params[:store_id]
  end

  def reset_password
    if password_params[:store_id].to_i == @staff.store_id
      status = @staff.reset_password!(password_params[:password], password_params[:password_confirmation])
      if status.success?
        redirect_to ems_store_staffs_path, notice: status.message
      else
        redirect_to pwd_ems_store_staff_path(params[:id], store_id: "#{password_params[:store_id]}"), notice: status.message
      end
    else
      redirect_to ems_store_staffs_path, notice: "无法修改其他酒店管理员!!"
    end
  end

  private
  def set_store_staff
    @staff = StoreStaff.find(params[:id])
  end

  def store_staff_params
    params[:store_staff][:store_id] = current_store.id
    params.require(:store_staff).permit(:full_name,
                                        :phone_number,
                                        :store_id,
                                        :password,
                                        :password_confirmation,
                                        :login_name,
                                        :employeed_at,
                                        :idcard,
                                        :numero,
                                        :store_department_id,
                                        :store_position_id,
                                        :status,
                                        :wechat,
                                        :education
                                      )
  end

  def password_params
    params.require(:store_staff).permit(
      :password,
      :password_confirmation,
      :store_id
    )
  end

end
